<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
//引入用户小仓库
import useUserStore from '@/store/modules/user'
import { User, Lock } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
let loginForm = reactive({ username: 'admin', password: '123456' })
let useStore = useUserStore()
let loginForms = ref()
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()
//定义变量控制按钮加载
let loading = ref(false)
const login = async () => {
  //校验表单通过才发请求
  await loginForms.value.validate()
  //加载按钮旋转
  loading.value = true
  //通知仓库来发送请求
  try {
    //可以书写。then的方法
    await useStore.userLogin(loginForm)
    //判断是否有路径参数，有就往query参数跳
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || '/' })
    //提示信息
    ElNotification({
      type: 'success',
      message: '登录成功',
      title: '你好~管理员',
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }

  //请求成功跳转到首页展示数据的地方
}
//定义表单校验对象
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [
    { required: true, min: 6, message: '密码至少六位', trigger: 'change' },
  ],
}
</script>
<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <!-- 表单 -->
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <el-image
            src="../../src/assets/images/login/login-logo.png"
            :lazy="true"
          ></el-image>
          <h2>外卖管理平台欢迎你</h2>
          <el-form-item label="账号" prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="login_btn"
              @click="login"
              :loading="loading"
            >
              立即登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/login/login-l.png') no-repeat;
  background-size: cover;
  padding: 40px;
  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: #fff;
    h2 {
      font-size: 20px;
      margin: 20px 0px;
    }
    .login_btn {
      width: 100%;
    }
  }
}
</style>
